package com.atguigu.controller;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.constant.RedisConst;
import com.atguigu.entity.UserInfo;
import com.atguigu.result.RetVal;
import com.atguigu.service.UserInfoService;
import com.atguigu.util.IpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private RedisTemplate redisTemplate;

    //实现登录的具体验证工作
    @PostMapping("/login")
    public RetVal login(@RequestBody UserInfo uiUserInfo, HttpServletRequest request){
        //a.根据用户账号密码从数据库中查询用户信息
        UserInfo dbUserInfo=userInfoService.queryUserFromDb(uiUserInfo);
        if(dbUserInfo!=null){
            //b.生成一个token/用户信息返回给页面cookie
            Map<String, Object> retValMap = new HashMap<>();
            String token = UUID.randomUUID().toString();
            retValMap.put("token",token);
            //用户昵称信息
            String nickName = dbUserInfo.getNickName();
            retValMap.put("nickName",nickName);
            /**c.将用户信息存放到redis当中
             * 用户信息的key 一个前缀+token
             * 存储的信息
             *  用户的id
             *  用户使用机器的ip地址
             */
            String userKey= RedisConst.USER_LOGIN_KEY_PREFIX+token;
            JSONObject loginInfo = new JSONObject();
            loginInfo.put("userId",dbUserInfo.getId());
            loginInfo.put("loginIp", IpUtil.getIpAddress(request));
            redisTemplate.opsForValue().set(userKey,loginInfo.toJSONString(),RedisConst.USERKEY_TIMEOUT, TimeUnit.SECONDS);
            return RetVal.ok(retValMap);
        }else{
            return RetVal.fail().message("登录失败");
        }
    }

    //2.退出登录
    @GetMapping("/logout")
    public RetVal logout(HttpServletRequest request){
//        String token=null;
//        Cookie[] cookies = request.getCookies();
//        for (Cookie cookie : cookies) {
//            if(cookie.getName().equals("token"));{
//                token= cookie.getValue();
//            }
//        }
        //如何得到token a.从cookie中去拿 b.从header当中去拿
        //从head当中能拿到token信息是因为 前端请求拦截器从cookie中拿到数据放入了header中
        String token = request.getHeader("token");
        String userKey=RedisConst.USER_LOGIN_KEY_PREFIX+token;
        redisTemplate.delete(userKey);
        return RetVal.ok();
    }
}
